<template>
  <VDialog
    @close="handleClose"
    :title="title"
    width="800"
    @save="save"
    :loading="loading"
    
  >
    <template #content>
      <div>
        <el-form
          ref="formRef"
          :model="formValues"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formValues.remark" type="textarea" />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="平台" prop="platform_id">
                <el-select
                  v-model="formValues.platform_id"
                  placeholder="请输入"
                  style="width: 100%"
                  filterable
                  clearable
                  @change="handlePlatformChange"
                >
                  <el-option
                    v-for="item in option.platformList"
                    :key="item.platform_id"
                    :label="item.platform_name"
                    :value="item.platform_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="站点">
                <el-select
                  v-model="formValues.site"
                  placeholder="请输入"
                  style="width: 100%"
                  filterable
                  clearable
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  @change="handleSiteChange"
                >
                  <el-option
                    v-for="item in dict.sitesList"
                    :key="item.site_id"
                    :label="item.site_abbrev"
                    :value="item.site_id"
                  />
                </el-select> </el-form-item
            ></el-col>
          </el-row>

          <el-form-item label="店铺">
            <el-select
              v-model="formValues.shop"
              placeholder="请输入"
              style="width: 100%"
              filterable
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
            >
              <el-option
                v-for="item in dict.shopList"
                :key="item.shop_id"
                :label="item.shop_name"
                :value="item.shop_id"
              />
            </el-select>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="原用户" prop="original_user_id">
                <VCascader
                  v-model="formValues.original_user_id"
                  collapse-tags
                  key="user_id"
                  style="width: 100%"
                  placeholder="原用户"
                  :isSelfStyle="false"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="新用户" prop="user_id">
                <VCascader
                  v-model="formValues.user_id"
                  :multiple="false"
                  key="user_id"
                  style="width: 100%"
                  placeholder="新用户"
                  :isSelfStyle="false"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="执行时间" prop="exec_time">
                <el-date-picker
                  v-model="formValues.exec_time"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="时间范围">
                <div class="flex w-full">
                  <el-date-picker
                    v-model="formValues.period_time"
                    type="daterange"
                    range-separator="-"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择"
                  />
                  <div class="mt-[10px] ml-[10px]">
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="目前只有订单数据支持按时间范围修改人员信息,该时间范围对应订单的'下单时间'"
                      placement="top"
                    >
                      <SvgIcon icon-class="hint_line" class="text-[16px]"/>
                    </el-tooltip>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="执行类型" prop="exec_type">
            <el-checkbox-group v-model="formValues.exec_type">
              <div v-for="(items, tag) in option.type" :key="items">
                <div class="my-[6px] font-bold flex items-center">
                  <span class="mr-[8px]">{{ tag }}</span>
                  <el-tooltip
                    v-if="tag == '头程' || tag == '订单'"
                    class="box-item"
                    effect="dark"
                    :content="tips[tag]"
                    placement="top"
                  >
                    <SvgIcon icon-class="hint_line" class="text-[16px]"/>
                  </el-tooltip>
                  <el-button link type="primary" @click="handelAll(items)"
                    >全选</el-button
                  >
                </div>
                <el-checkbox
                  :label="item.id"
                  v-for="item in items"
                  :key="item.id"
                  >{{ item.name }}</el-checkbox
                >
              </div>
            </el-checkbox-group>
            <!-- <el-select
              v-model="formValues.exec_type"
              placeholder="请输入"
              style="width: 100%"
              filterable
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
            >
              <el-option
                v-for="item in option.type"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="!item?.status"
              />
            </el-select> -->
          </el-form-item>
        </el-form>
      </div>
    </template>
  </VDialog>
</template>
<script setup lang="jsx">
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ElMessage } from "element-plus";
import { transferAdd, transferEdit, transferDetail } from "../api.js";
import { formatToDate, formatDateTime } from "@/utils/time.js";
const props = defineProps({
  data: { type: Object, default: () => ({}) },
  title: { type: String, default: "新增" },
  option: { type: Object, default: () => ({}) },
});
const loading = ref(false);
const { option } = toRefs(props);
const emit = defineEmits(["update:modelValue", "refresh", "close"]);
const formValues = ref({});
const rules = reactive({
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
  platform_id: [{ required: true, message: "请选择平台", trigger: "blur" }],
  original_user_id: [
    { required: true, message: "请选择原用户", trigger: "blur" },
  ],
  user_id: [{ required: true, message: "请选择新用户", trigger: "blur" }],
  exec_time: [{ required: true, message: "请选择执行时间", trigger: "blur" }],
  exec_type: [{ required: true, message: "请选择执行类型", trigger: "blur" }],
});
const isEdit = computed(() => !!props.data);
watch(
  () => props.data,
  () => {
    if (!props.data) return;
    let data = JSON.parse(JSON.stringify(props.data));
    data.site = data?.site?.map((d) => d.site_id) || [];
    data.shop = data?.shop?.map((d) => d.shop_id) || [];
    handlePlatformChange(data.platform_id);
    handleSiteChange(data.site);
    const { period_end_time, period_start_time } = data;
    formValues.value = {
      ...data,
      period_time: period_start_time
        ? [formatToDate(period_start_time), formatToDate(period_end_time)]
        : [],
    };
  }
);
const tips = {
  头程: "只修改未完结单据的人员信息",
  订单: "支持修改指定[下单时间]范围内订单的销售/客服人员,若不选择时间范围,则修改所有符合条件的订单",
};
const formRef = ref();
const dict = reactive({
  shopList: [], // 店铺
  sitesList: [], // 站点
});

const handlePlatformChange = (val) => {
  dict.sitesList = [];
  formValues.value.site = [];
  dict.shopList = [];
  formValues.value.shop = [];
  let data = option.value?.platformList?.find((d) => d.platform_id == val);
  dict.sitesList = data?.sites || [];
};
const handleSiteChange = (val) => {
  formValues.value.shop = [];
  dict.shopList = [];
  let data = option.value.shopList?.filter((d) => val?.includes(d.site_id));
  dict.shopList = data;
};
// const handelAll = (items) => {
//   if (!Array.isArray(formValues.value.exec_type)) {
//     formValues.value.exec_type = [];
//   }
//   const ids = new Set([
//     ...formValues.value.exec_type,
//     ...(items?.map((item) => item.id) || []),
//   ]);
//   formValues.value.exec_type = Array.from(ids);
// };
const handelAll = (items) => {
  if (!Array.isArray(formValues.value.exec_type)) {
    formValues.value.exec_type = [];
  }

  const selected = new Set(formValues.value.exec_type);
  const itemIds = items.map(item => item.id);
  const isAllSelected = itemIds.every(id => selected.has(id));

  if (isAllSelected) {
    // 如果已全选，则移除这些 id
    formValues.value.exec_type = formValues.value.exec_type.filter(id => !itemIds.includes(id));
  } else {
    // 如果未全选，则添加这些 id（去重）
    formValues.value.exec_type = Array.from(new Set([...formValues.value.exec_type, ...itemIds]));
  }
};
const save = async () => {
  try {
    formRef.value?.validate(async (valid) => {
      if (!valid) return false;
      const { platform_id, shop, site, period_time } = formValues.value;
      let data = {
        ...formValues.value,
        platform: option.value.platformList.find(
          (d) => d.platform_id === platform_id
        )?.platform_name,
        shop: dict.shopList.filter((d) => shop.includes(d.shop_id)),
        site: dict.sitesList.filter((d) => site.includes(d.site_id)),
        period_start_time: formatDateTime(period_time?.[0], "start"),
        period_end_time: formatDateTime(period_time?.[1], "end"),
        period_time: undefined,
      };
      const { code, message } = await (isEdit.value
        ? transferEdit
        : transferAdd)({
        ...data,
      });
      if (code !== 200) {
        ElMessage.error(message);
        return;
      }
      ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
      handleClose(true);
    });
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const handleClose = async (refresh) => {
  formValues.value = {};
  dict.shopList = [];
  dict.sitesList = [];
  // surchargeData.value = []
  await nextTick();
  formRef.value.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
<style lang="scss" scoped>
:deep(.el-form-item__label) {
  pointer-events: none;
}
</style>
